<!--
 * @Author: weidewei
 * @Date: 2025-04-15 13:47:08
 * @LastEditors: weidewei
 * @LastEditTime: 2025-07-01 20:03:06
 * @Description: 
 * @FilePath: \koca_jrjg_web\src\components\CompDynamicTableAdmin\DialogByFieldOperate.vue
-->
<template>
  <comp-el-dialog
    width="800px"
    :title="'单元格编辑'"
    :show-close-button="action === 'view'"
    @closed="handleDialogClosed"
    :dialog-confirm="handleConfirm"
  >
    <form-create v-model:api="formApi" :rule="formRules" :option="formOptions" />
  </comp-el-dialog>
</template>
<script lang="ts" setup>
  import { updateCell } from "@api/tools-module/api-report-manager-mgt";
  const props = defineProps({
    dialogData: {
      type: Object,
      default: () => ({}),
    },
    action: {
      type: String,
      default: "",
    },
  });
  const { proxy } = getCurrentInstance()!;
  const formApi: any = shallowRef(null);
  const formRules = ref([
    {
      type: "hidden",
      field: "id",
    },
    {
      type: "comp-number-input",
      field: "cellRow",
      title: "行号",
      props: {
        minDecimal: 0,
        maxDecimal: 0,
      },
      validate: true,
      col: { span: 12 },
    },
    {
      type: "comp-number-input",
      field: "cellCol",
      title: "列号",
      props: {
        minDecimal: 0,
        maxDecimal: 0,
      },
      validate: true,
      col: { span: 12 },
    },
    {
      type: "comp-number-input",
      field: "mergedRowCount",
      title: "行合并",
      props: {
        minDecimal: 0,
        maxDecimal: 0,
      },
      validate: true,
      col: { span: 12 },
    },
    {
      type: "comp-number-input",
      field: "mergedColCount",
      title: "列合并",
      props: {
        minDecimal: 0,
        maxDecimal: 0,
      },
      validate: true,
      col: { span: 12 },
    },
    {
      type: "select",
      field: "cellType",
      title: "单元格类型",
      options: proxy?.$dict.queryDictItems("CELL_TYPE"),
      on: {
        change: (data) => {
          hiddenFields(data);
        },
      },
      validate: true,
      col: { span: 12 },
    },
    {
      type: "select",
      field: "isRequired",
      title: "是否必填",
      value: "1",
      options: proxy?.$dict.queryDictItems("API_PARA_REQUIRED"),
      validate: true,
      col: { span: 12 },
    },
    {
      type: "select",
      field: "inputType",
      title: "输入类型",
      options: proxy?.$dict.queryDictItems("INPUT_TYPE"),
      validate: true,
      col: { span: 12 },
    },
    {
      type: "input",
      field: "cellDictId",
      title: "字典ID",
      validate: false,
      col: { span: 12 },
    },
    {
      type: "select",
      field: "isSync",
      title: "是否同步数据源表",
      options: proxy?.$dict.queryDictItems("API_PARA_REQUIRED"),
      validate: true,
      col: { span: 12 },
    },
    {
      type: "input",
      field: "tableName",
      title: "映射表名",
      validate: true,
      col: { span: 12 },
    },
    {
      type: "input",
      field: "cellTableField",
      title: "映射表字段名",
      validate: true,
      col: { span: 12 },
    },
    {
      type: "input",
      field: "colWidth", // 默认值为150px
      title: "单元格宽度",
      col: { span: 12 },
    },
    {
      type: "input",
      field: "rowHeight",
      title: "单元格高度", // 默认值为auto
      col: { span: 12 },
    },
    {
      type: "input",
      field: "relyTable",
      title: "默认数据源表",
      col: { span: 12 },
    },
    {
      type: "input",
      field: "relyTableField",
      title: "默认数据源表字典",
      col: { span: 12 },
    },
    {
      type: "input",
      field: "cellDefaultValue",
      title: "默认值",
      col: { span: 24 },
    },
    {
      type: "input",
      field: "cellText",
      title: "字段中文名",
      col: { span: 24 },
    },
    {
      type: "input",
      field: "isForbid",
      title: "禁止输入字段",
      col: { span: 24 },
    },
    {
      type: "input",
      field: "fieldShowText",
      title: "文本内容",
      props: {
        type: "textarea",
        rows: 3,
      },
      validate: true,
      col: { span: 24 },
    },
    {
      type: "input",
      field: "cellCheckRule",
      title: "验证规则",
      props: {
        type: "textarea",
        rows: 3,
      },
      col: { span: 24 },
    },
    {
      type: "input",
      field: "inputTip",
      title: "输入提示",
      props: {
        type: "textarea",
        rows: 3,
      },
      col: { span: 24 },
    },
    {
      type: "comp-code-editor",
      field: "controlScript",
      title: "验证脚本",
      props: {
        options: {
          mode: "application/json",
        },
      },
      col: { span: 24 },
    },
    {
      type: "comp-code-editor",
      title: "单元格样式",
      field: "cellStyle",
      props: {
        options: {
          mode: "application/json",
        },
      },
      col: { span: 24 },
    },
  ]);
  const formOptions = {
    form: {
      labelWidth: "1.4rem",
      inline: false,
    },
  };

  const refreshExcelTable: any = inject("refreshExcelTable");

  onMounted(() => {
    nextTick(() => {
      initData();
    });
  });

  function initData() {
    const detailData = { ...props.dialogData };
    detailData.cellCheckRule = safeDecode(detailData.cellCheckRule);
    detailData.controlScript = safeDecode(detailData.controlScript);
    formApi.value.setValue(detailData);
    hiddenFields(detailData.cellType);
  }

  function isValidBase64(str: string): boolean {
    try {
      return globalThis.btoa(globalThis.atob(str)) === str;
    } catch (e) {
      return false;
    }
  }

  function safeDecode(encodedStr: string): string {
    if (!encodedStr) return "";
    try {
      const uriDecoded = decodeURIComponent(encodedStr);
      if (isValidBase64(uriDecoded)) {
        return globalThis.atob(uriDecoded);
      }
      return encodedStr;
    } catch (e) {
      console.error("解码失败:", e);
      return encodedStr;
    }
  }

  // 根据输入框类型隐藏字段
  function hiddenFields(cellType) {
    if (cellType === "show") {
      formApi.value.hidden(true, [
        "inputType",
        "cellDictId",
        "isSync",
        "tableName",
        "cellTableField",
        "relyTable",
        "relyTableField",
        "cellDefaultValue",
        "cellText",
        "isForbid",
        "cellCheckRule",
        "controlScript",
        "isRequired",
      ]);
    } else {
      formApi.value.hidden(false);
      formApi.value.hidden(true, ["fieldShowText", "cellStyle"]);
    }
  }

  const $emit = defineEmits(["dialog-confirm", "update:dialog-status"]);

  function handleConfirm(resolve, reject) {
    const formData = formApi.value.formData();
    if (formData.cellCheckRule) {
      try {
        formData.cellCheckRule = encodeURIComponent(btoa(formData.cellCheckRule));
      } catch (e) {
        console.error("编码失败:", e);
        formData.cellCheckRule = "";
      }
    }
    if (formData.controlScript) {
      try {
        formData.controlScript = encodeURIComponent(btoa(formData.controlScript));
      } catch (e) {
        console.error("编码失败:", e);
        formData.controlScript = "";
      }
    }
    formApi.value
      .validate()
      .then(() => {
        (proxy as any)?.$http
          .post(updateCell, {dto:formData})
          .then(() => {
            proxy?.$showToast("保存成功", "success");
            $emit("dialog-confirm");
            refreshExcelTable();
            resolve();
          })
          .catch((err) => {
            reject();
          });
      })
      .catch(() => {
        reject();
      });
  }

  // function getFormData() {
  //   return new Promise((resolve,reject)=>{

  //   })
  // }

  function handleDialogClosed() {
    $emit("update:dialog-status", false);
  }
</script>
